package com.liao.controller;

import com.liao.bean.News;
import com.liao.bean.Order;
import com.liao.bean.result.Code;
import com.liao.bean.result.Msg;
import com.liao.bean.result.PageResult;
import com.liao.bean.result.Result;
import com.liao.service.NewsService;
import com.liao.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @ResponseBody
    @RequestMapping("/queryNewsListByPage")
    public PageResult<News> queryNewsListByPage(@RequestParam(defaultValue = "1") Integer currentPage,
                                                  @RequestParam(defaultValue = "5") Integer pageSize,
                                                  @RequestParam(defaultValue = "") String newsTitle) throws Exception {
        PageResult<News> pageResult = newsService.queryNewsListByPage(currentPage,pageSize,newsTitle);
        return pageResult;
    }

    @ResponseBody
    @RequestMapping("/addNews")
    public Result addNews(@RequestBody News news) throws Exception {

        newsService.addNews(news);
        return new Result(true, Code.NEWS_ADD_SUCCESS, Msg.NEWS_ADD_SUCCESS);

    }

    @ResponseBody
    @RequestMapping("/editNews")
    public Result editNews( @RequestBody News news) throws Exception {
        newsService.editNews(news);
        return new Result(true,Code.NEWS_EDIT_SUCCESS, Msg.NEWS_EDIT_SUCCESS);
    }

    @ResponseBody
    @RequestMapping("/deleteNews")
    public Result deleteNews(String newsId) throws Exception {
        newsService.deleteNews(newsId);
        return new Result(true,Code.NEWS_DELETE_SUCCESS, Msg.NEWS_DELETE_SUCCESS);
    }

    @ResponseBody
    @RequestMapping("/deleteNewsIds")
    public Result deleteNewsIds(@RequestParam("newsIds[]") List<String> newsIds) throws Exception {
        for (String newsId : newsIds) {
            try {
                newsService.deleteNews(newsId);
            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,Code.NEWS_DELETE_FAIL, Msg.NEWS_DELETE_FAIL);
            }

        }
        return new Result(true,Code.NEWS_DELETE_SUCCESS, Msg.NEWS_DELETE_SUCCESS);
    }
}
